package co.edu.usbcali.sam.presentation.backingBeans;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.TimeZone;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.event.ActionEvent;

import org.primefaces.component.commandbutton.CommandButton;
import org.primefaces.component.commandlink.CommandLink;
import org.primefaces.component.inputtext.InputText;
import org.primefaces.context.RequestContext;

import co.edu.usbcali.sam.exceptions.ZMessManager;
import co.edu.usbcali.sam.modelo.Calificaciones;
import co.edu.usbcali.sam.modelo.Estudiantes;
import co.edu.usbcali.sam.modelo.MatriculaAcademica;
import co.edu.usbcali.sam.modelo.MatriculaAsignatura;
import co.edu.usbcali.sam.modelo.dto.AsignaturasDTO;
import co.edu.usbcali.sam.modelo.dto.MatriculaAsignaturaDTO;
import co.edu.usbcali.sam.presentation.businessDelegate.IBusinessDelegatorView;
import co.edu.usbcali.sam.presentation.datamodel.AsignaturaDataModel;
import co.edu.usbcali.sam.utilities.FacesUtils;

/**
 * @author Zathura Code Generator http://code.google.com/p/zathura
 * www.zathuracode.org
 *
 */
@ManagedBean
@ViewScoped
public class MatriculaAsignaturaView implements Serializable {
    private static final long serialVersionUID = 1L;
    private InputText txtInasistencias;
    private InputText txtIdAsignatura_Asignaturas;
    private InputText txtIdCali_Calificaciones;
    private InputText txtIdMatAca_MatriculaAcademica;
    private InputText txtIdMatAsig;
    private CommandButton btnSave;
    private CommandButton btnModify;
    private CommandButton btnDelete;
    private CommandButton btnClear;
    private CommandButton btnCrear;
    private CommandLink btnExpotar;
    private List<MatriculaAsignaturaDTO> data;
    private List<AsignaturasDTO> dataAsignatura;
    private MatriculaAsignaturaDTO selectedMatriculaAsignatura;
    private MatriculaAsignatura entity;
    private boolean showDialog;
    private AsignaturasDTO selectedAsignatura;
    private AsignaturaDataModel asignaturaModel;
    private AsignaturasDTO selectedAsignatura2;
    private AsignaturaDataModel asignaturaModel2;
    private List<AsignaturasDTO> asignaturasMatriculadas;
    @ManagedProperty(value = "#{BusinessDelegatorView}")
    private IBusinessDelegatorView businessDelegatorView;

    public MatriculaAsignaturaView() {
        super();
    }

    ////////////////////////////////////////////////////////////////////////////
  	public void cerrar() {

  		btnSave.setDisabled(true);
  		//btnModify.setDisabled(false);
  		//btnCrear.setDisabled(false);
  	}
  	
  	MatriculaAcademica m;
  	
  	public String adicionar(){

  		try {
  			if(m==null){
  				Estudiantes e = businessDelegatorView.getEstudiantes(businessDelegatorView.consultarIdEstudiantexLogin(FacesUtils.login()));
  				//Estudiantes e = businessDelegatorView.getEstudiantes(1L);
  				m=new MatriculaAcademica();
  				m.setEstudiantes(e);
  	  			m.setAnoLectivo("2014-2015");
  	  			businessDelegatorView.saveMatriculaAcademica(m);
  	  		}
 		
  		if(asignaturasMatriculadas==null){
  			asignaturasMatriculadas=new ArrayList<AsignaturasDTO>();
  		}
  		
  		if(asignaturasMatriculadas.size()==0){
  			asignaturasMatriculadas.add(selectedAsignatura);
  			asignaturaModel2=new AsignaturaDataModel(asignaturasMatriculadas);
  			RequestContext.getCurrentInstance().execute("PF('singleCarDialog').hide()");

  		}else{

  			for (int i = 0; i < asignaturasMatriculadas.size(); i++) {
				if(asignaturasMatriculadas.get(i).getIdAsignatura().toString().equals(selectedAsignatura.getIdAsignatura()+"")){
					 FacesUtils.addErrorMessage("La Asignatura ya se encuentra en la matricula");
					return "";
				}
			}
  			
  			asignaturasMatriculadas.add(selectedAsignatura);
  			asignaturaModel2=new AsignaturaDataModel(asignaturasMatriculadas);
  			RequestContext.getCurrentInstance().execute("PF('singleCarDialog').hide()");
  			
  		}
  		
  		} catch (Exception e1) {
			e1.printStackTrace();
		}
  		
  		return "";
  	}
  	
  	public String quitar(){
  		
  		for (int i = 0; i < asignaturasMatriculadas.size(); i++) {
			if(asignaturasMatriculadas.get(i).toString().equals(selectedAsignatura2.getIdAsignatura()+"")){
				asignaturasMatriculadas.remove(i);
			}
		}
  		  		
  		return "";
  	}
  	
  	
  	public String guardarMatricula(){
  		
  		for (int i = 0; i < asignaturasMatriculadas.size(); i++) {
  			try {
  	  			MatriculaAsignatura ma=new MatriculaAsignatura();
  				ma.setMatriculaAcademica(m);
  				ma.setAsignaturas(businessDelegatorView.getAsignaturas(asignaturasMatriculadas.get(i).getIdAsignatura()));	
  				Calificaciones ca=new Calificaciones();
  				businessDelegatorView.saveCalificaciones(ca);
  				ma.setCalificaciones(ca);
  				businessDelegatorView.saveMatriculaAsignatura(ma);
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
  		
  		btnExpotar.setDisabled(false);
  		FacesUtils.addInfoMessage("La matricula Academica se creo con Exito");
  		
  		return "";
  	}
  	
  	/////////////////////////////////////////////////////////////////////////////
    

    public String action_new() {
        action_clear();
        selectedMatriculaAsignatura = null;
        setShowDialog(true);

        return "";
    }

    public String action_clear() {
        entity = null;
        selectedMatriculaAsignatura = null;

        if (txtInasistencias != null) {
            txtInasistencias.setValue(null);
            txtInasistencias.setDisabled(true);
        }

        if (txtIdAsignatura_Asignaturas != null) {
            txtIdAsignatura_Asignaturas.setValue(null);
            txtIdAsignatura_Asignaturas.setDisabled(true);
        }

        if (txtIdCali_Calificaciones != null) {
            txtIdCali_Calificaciones.setValue(null);
            txtIdCali_Calificaciones.setDisabled(true);
        }

        if (txtIdMatAca_MatriculaAcademica != null) {
            txtIdMatAca_MatriculaAcademica.setValue(null);
            txtIdMatAca_MatriculaAcademica.setDisabled(true);
        }

        if (txtIdMatAsig != null) {
            txtIdMatAsig.setValue(null);
            txtIdMatAsig.setDisabled(false);
        }

        if (btnSave != null) {
            btnSave.setDisabled(true);
        }

        if (btnDelete != null) {
            btnDelete.setDisabled(true);
        }

        return "";
    }

    public String action_edit(ActionEvent evt) {
        selectedMatriculaAsignatura = (MatriculaAsignaturaDTO) (evt.getComponent()
                                                                   .getAttributes()
                                                                   .get("selectedMatriculaAsignatura"));
        txtInasistencias.setValue(selectedMatriculaAsignatura.getInasistencias());
        txtInasistencias.setDisabled(false);
        txtIdAsignatura_Asignaturas.setValue(selectedMatriculaAsignatura.getIdAsignatura_Asignaturas());
        txtIdAsignatura_Asignaturas.setDisabled(false);
        txtIdCali_Calificaciones.setValue(selectedMatriculaAsignatura.getIdCali_Calificaciones());
        txtIdCali_Calificaciones.setDisabled(false);
        txtIdMatAca_MatriculaAcademica.setValue(selectedMatriculaAsignatura.getIdMatAca_MatriculaAcademica());
        txtIdMatAca_MatriculaAcademica.setDisabled(false);
        txtIdMatAsig.setValue(selectedMatriculaAsignatura.getIdMatAsig());
        txtIdMatAsig.setDisabled(true);
        btnSave.setDisabled(false);
        setShowDialog(true);

        return "";
    }

    public String action_save() {
        try {
            if ((selectedMatriculaAsignatura == null) && (entity == null)) {
                action_create();
            } else {
                action_modify();
            }

            data = null;
        } catch (Exception e) {
            FacesUtils.addErrorMessage(e.getMessage());
        }

        return "";
    }

    public String action_create() {
        try {
            entity = new MatriculaAsignatura();

            Long idMatAsig = FacesUtils.checkLong(txtIdMatAsig);

            entity.setIdMatAsig(idMatAsig);
            entity.setInasistencias(FacesUtils.checkLong(txtInasistencias));
            entity.setAsignaturas((FacesUtils.checkLong(
                    txtIdAsignatura_Asignaturas) != null)
                ? businessDelegatorView.getAsignaturas(FacesUtils.checkLong(
                        txtIdAsignatura_Asignaturas)) : null);
            entity.setCalificaciones((FacesUtils.checkLong(
                    txtIdCali_Calificaciones) != null)
                ? businessDelegatorView.getCalificaciones(FacesUtils.checkLong(
                        txtIdCali_Calificaciones)) : null);
            entity.setMatriculaAcademica((FacesUtils.checkLong(
                    txtIdMatAca_MatriculaAcademica) != null)
                ? businessDelegatorView.getMatriculaAcademica(
                    FacesUtils.checkLong(txtIdMatAca_MatriculaAcademica)) : null);
            businessDelegatorView.saveMatriculaAsignatura(entity);
            FacesUtils.addInfoMessage(ZMessManager.ENTITY_SUCCESFULLYSAVED);
            action_clear();
        } catch (Exception e) {
            entity = null;
            FacesUtils.addErrorMessage(e.getMessage());
        }

        return "";
    }

    public String action_modify() {
        try {
            if (entity == null) {
                Long idMatAsig = new Long(selectedMatriculaAsignatura.getIdMatAsig());
                entity = businessDelegatorView.getMatriculaAsignatura(idMatAsig);
            }

            entity.setInasistencias(FacesUtils.checkLong(txtInasistencias));
            entity.setAsignaturas((FacesUtils.checkLong(
                    txtIdAsignatura_Asignaturas) != null)
                ? businessDelegatorView.getAsignaturas(FacesUtils.checkLong(
                        txtIdAsignatura_Asignaturas)) : null);
            entity.setCalificaciones((FacesUtils.checkLong(
                    txtIdCali_Calificaciones) != null)
                ? businessDelegatorView.getCalificaciones(FacesUtils.checkLong(
                        txtIdCali_Calificaciones)) : null);
            entity.setMatriculaAcademica((FacesUtils.checkLong(
                    txtIdMatAca_MatriculaAcademica) != null)
                ? businessDelegatorView.getMatriculaAcademica(
                    FacesUtils.checkLong(txtIdMatAca_MatriculaAcademica)) : null);
            businessDelegatorView.updateMatriculaAsignatura(entity);
            FacesUtils.addInfoMessage(ZMessManager.ENTITY_SUCCESFULLYMODIFIED);
        } catch (Exception e) {
            data = null;
            FacesUtils.addErrorMessage(e.getMessage());
        }

        return "";
    }

    public String action_delete_datatable(ActionEvent evt) {
        try {
            selectedMatriculaAsignatura = (MatriculaAsignaturaDTO) (evt.getComponent()
                                                                       .getAttributes()
                                                                       .get("selectedMatriculaAsignatura"));

            Long idMatAsig = new Long(selectedMatriculaAsignatura.getIdMatAsig());
            entity = businessDelegatorView.getMatriculaAsignatura(idMatAsig);
            action_delete();
        } catch (Exception e) {
            FacesUtils.addErrorMessage(e.getMessage());
        }

        return "";
    }

    public String action_delete_master() {
        try {
            Long idMatAsig = FacesUtils.checkLong(txtIdMatAsig);
            entity = businessDelegatorView.getMatriculaAsignatura(idMatAsig);
            action_delete();
        } catch (Exception e) {
            FacesUtils.addErrorMessage(e.getMessage());
        }

        return "";
    }

    public void action_delete() throws Exception {
        try {
            businessDelegatorView.deleteMatriculaAsignatura(entity);
            FacesUtils.addInfoMessage(ZMessManager.ENTITY_SUCCESFULLYDELETED);
            action_clear();
            data = null;
        } catch (Exception e) {
            throw e;
        }
    }

    public String action_closeDialog() {
        setShowDialog(false);
        action_clear();

        return "";
    }

    public String actionDeleteDataTableEditable(ActionEvent evt) {
        try {
            selectedMatriculaAsignatura = (MatriculaAsignaturaDTO) (evt.getComponent()
                                                                       .getAttributes()
                                                                       .get("selectedMatriculaAsignatura"));

            Long idMatAsig = new Long(selectedMatriculaAsignatura.getIdMatAsig());
            entity = businessDelegatorView.getMatriculaAsignatura(idMatAsig);
            businessDelegatorView.deleteMatriculaAsignatura(entity);
            data.remove(selectedMatriculaAsignatura);
            FacesUtils.addInfoMessage(ZMessManager.ENTITY_SUCCESFULLYDELETED);
            action_clear();
        } catch (Exception e) {
            FacesUtils.addErrorMessage(e.getMessage());
        }

        return "";
    }

    public String action_modifyWitDTO(Long idMatAsig, Long inasistencias,
        Long idAsignatura_Asignaturas, Long idCali_Calificaciones,
        Long idMatAca_MatriculaAcademica) throws Exception {
        try {
            entity.setInasistencias(FacesUtils.checkLong(inasistencias));
            businessDelegatorView.updateMatriculaAsignatura(entity);
            FacesUtils.addInfoMessage(ZMessManager.ENTITY_SUCCESFULLYMODIFIED);
        } catch (Exception e) {
            
            FacesUtils.addErrorMessage(e.getMessage());
            throw e;
        }

        return "";
    }

    public InputText getTxtInasistencias() {
        return txtInasistencias;
    }

    public void setTxtInasistencias(InputText txtInasistencias) {
        this.txtInasistencias = txtInasistencias;
    }

    public InputText getTxtIdAsignatura_Asignaturas() {
        return txtIdAsignatura_Asignaturas;
    }

    public void setTxtIdAsignatura_Asignaturas(
        InputText txtIdAsignatura_Asignaturas) {
        this.txtIdAsignatura_Asignaturas = txtIdAsignatura_Asignaturas;
    }

    public InputText getTxtIdCali_Calificaciones() {
        return txtIdCali_Calificaciones;
    }

    public void setTxtIdCali_Calificaciones(InputText txtIdCali_Calificaciones) {
        this.txtIdCali_Calificaciones = txtIdCali_Calificaciones;
    }

    public InputText getTxtIdMatAca_MatriculaAcademica() {
        return txtIdMatAca_MatriculaAcademica;
    }

    public void setTxtIdMatAca_MatriculaAcademica(
        InputText txtIdMatAca_MatriculaAcademica) {
        this.txtIdMatAca_MatriculaAcademica = txtIdMatAca_MatriculaAcademica;
    }

    public InputText getTxtIdMatAsig() {
        return txtIdMatAsig;
    }

    public void setTxtIdMatAsig(InputText txtIdMatAsig) {
        this.txtIdMatAsig = txtIdMatAsig;
    }

    public List<MatriculaAsignaturaDTO> getData() {
        try {
            if (data == null) {
                data = businessDelegatorView.getDataMatriculaAsignatura();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return data;
    }

    public void setData(List<MatriculaAsignaturaDTO> matriculaAsignaturaDTO) {
        this.data = matriculaAsignaturaDTO;
    }

    public MatriculaAsignaturaDTO getSelectedMatriculaAsignatura() {
        return selectedMatriculaAsignatura;
    }

    public void setSelectedMatriculaAsignatura(
        MatriculaAsignaturaDTO matriculaAsignatura) {
        this.selectedMatriculaAsignatura = matriculaAsignatura;
    }

    public CommandButton getBtnSave() {
        return btnSave;
    }

    public void setBtnSave(CommandButton btnSave) {
        this.btnSave = btnSave;
    }

    public CommandButton getBtnModify() {
        return btnModify;
    }

    public void setBtnModify(CommandButton btnModify) {
        this.btnModify = btnModify;
    }

    public CommandButton getBtnDelete() {
        return btnDelete;
    }

    public void setBtnDelete(CommandButton btnDelete) {
        this.btnDelete = btnDelete;
    }

    public CommandButton getBtnClear() {
        return btnClear;
    }

    public void setBtnClear(CommandButton btnClear) {
        this.btnClear = btnClear;
    }

    public TimeZone getTimeZone() {
        return java.util.TimeZone.getDefault();
    }

    public IBusinessDelegatorView getBusinessDelegatorView() {
        return businessDelegatorView;
    }

    public void setBusinessDelegatorView(
        IBusinessDelegatorView businessDelegatorView) {
        this.businessDelegatorView = businessDelegatorView;
    }

    public boolean isShowDialog() {
        return showDialog;
    }

    public void setShowDialog(boolean showDialog) {
        this.showDialog = showDialog;
    }

	public CommandButton getBtnCrear() {
		return btnCrear;
	}

	public void setBtnCrear(CommandButton btnCrear) {
		this.btnCrear = btnCrear;
	}

	public AsignaturaDataModel getAsignaturaModel() {
		try {
			if(asignaturaModel==null){
				asignaturaModel=new AsignaturaDataModel(getDataAsignatura());	
			}
		} catch (Exception e) {
		}

		return asignaturaModel;
	}

	public void setAsignaturaModel(AsignaturaDataModel asignaturaModel) {
		this.asignaturaModel = asignaturaModel;
	}

	public List<AsignaturasDTO> getDataAsignatura() {
		try {
			if(dataAsignatura==null){
				dataAsignatura=businessDelegatorView.getDataAsignaturas();
			}
		} catch (Exception e) {
		}

		return dataAsignatura;
	}

	public void setDataAsignatura(List<AsignaturasDTO> dataAsignatura) {
		this.dataAsignatura = dataAsignatura;
	}

	public AsignaturasDTO getSelectedAsignatura() {
		return selectedAsignatura;
	}

	public void setSelectedAsignatura(AsignaturasDTO selectedAsignatura) {
		this.selectedAsignatura = selectedAsignatura;
	}

	public AsignaturasDTO getSelectedAsignatura2() {
		return selectedAsignatura2;
	}

	public void setSelectedAsignatura2(AsignaturasDTO selectedAsignatura2) {
		this.selectedAsignatura2 = selectedAsignatura2;
	}

	public AsignaturaDataModel getAsignaturaModel2() {
		if(asignaturaModel2==null){
			asignaturaModel2=new AsignaturaDataModel();
		}
		return asignaturaModel2;
	}

	public void setAsignaturaModel2(AsignaturaDataModel asignaturaModel2) {
		this.asignaturaModel2 = asignaturaModel2;
	}

	public CommandLink getBtnExpotar() {
		return btnExpotar;
	}

	public void setBtnExpotar(CommandLink btnExpotar) {
		this.btnExpotar = btnExpotar;
	}
	
	
		
}
